<template>
  <div class="whole-page">
    <el-container>
      <el-header>
        <el-row class="header-row">
          <el-col :span="12">
            <h1 style="font-size: 32px;">{{ display_name }}<span class="info">（{{ type }}）&nbsp;&nbsp;<a v-if="homepage_url" @click="toUrl(homepage_url)">期刊主页</a></span></h1>
            <div class="headMain">
              <span>文章数量：{{ works_count }}</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ISSN：<span v-if="issn_l">{{ issn_l }}</span><span v-else>暂无ISSN号码</span></span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;H指数：{{ h_index }}</span>
              <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;国家代码：{{ country_code }}</span>
              <p></p>
            </div>
          </el-col>
          <el-col :span="12" class="search-col">
            <el-form :inline="true">
              <el-form-item label="搜索期刊内文章:">
                <el-select v-model="searchOption" placeholder="选择搜索项" class="option">
                  <el-option label="全部" value="all" />
                  <el-option label="标题" value="title" />
                  <el-option label="作者" value="author" />
                  <el-option label="日期" value="date" />
                </el-select>
                <el-input v-model="searchTerm" @input="searchWorks" class="input" clearable />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-header>
      <el-scrollbar>
        <el-main class="main-content">
          <el-table :data="works_show" height="670" stripe style="width: 100%">
            <el-table-column prop="title" label="标题"></el-table-column>
            <el-table-column label="作者">
              <template #default="scope">
                <span v-for="(authorship, index) in scope.row.authorships" :key="index">
                  <a @click.stop="toScholar(authorship.author.id)">{{ authorship.author.display_name }}</a>
                  {{ index < scope.row.authorships.length - 1 ? ', ' : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="publication_date" label="出版日期"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button @click.stop="goTo(scope.row.id)" type="primary" size="mini">跳转</el-button>
                <el-button 
                  v-if="scope.row.primary_location.pdf_url && scope.row.primary_location.pdf_url.trim() !== ''"
                  @click.stop="downloadWork(scope.row.primary_location.pdf_url)" 
                  type="success" 
                  size="mini" >
                  下载地址
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              layout="prev, pager, next, jumper"
              :total="works_search.length"
            />
          </div>
        </el-main>
      </el-scrollbar>
    </el-container>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { req_getVenueInfo, req_getPapersByPrimaryLocation } from '../../../api/index.ts';

export default {
  name: "VenueView",
  data() {
    return {
      venueId: "",
      display_name: "未知期刊",
      works_count: 0,
      issn_l: 0,
      works_show: [],
      works_search: [],
      works_list: [],
      authorships: [],
      searchTerm: '',
      searchOption: 'all', // 默认搜索项为全部
      currentPage: 1,
      pageSize: 10, // 每页显示的数量
      type: '',
      h_index: 0,
      country_code: '',
      homepage_url: '',
    };
  },
  mounted() {
    this.venueId = this.$route.params.venue_id;
    this.getVenueInfo(this.venueId);
    this.initializeWorksList();
  },
  methods: {
    initializeWorksList() {
      this.works_search = this.works_list;
      this.updateWorksShow();
    },
    getVenueInfo(venueId) {
      req_getVenueInfo(venueId).then(res => {
        const errno = res.data.errno;
        const msg = res.data.msg;
        if (errno === 1) {
          this.h_index = res.data.venue.summary_stats.h_index;
          this.type = res.data.venue.type;
          this.country_code = res.data.venue.country_code;
          this.homepage_url = res.data.venue.homepage_url;
          this.display_name = res.data.venue.display_name;
          this.works_count = res.data.venue.works_count;
          this.issn_l = res.data.venue.issn_l;
          // ElMessage.info(msg);
        } else if ([1001, 1002, 1003, 2001, 2002].includes(errno)) {
          ElMessage.info(msg);
        } else {
          console.error('Error getting venue:', msg);
        }
      }).catch(error => {
        console.error('Error getting venue:', error);
      });

      req_getPapersByPrimaryLocation(venueId).then(res =>{
        const errno = res.data.errno;
        const msg = res.data.msg;
        if (errno === 1) {
          this.works_list = res.data.results;
          this.works_search = this.works_list;
          this.authorships = res.data.results.authorships;
          this.updateWorksShow();
        } else if ([1001, 1002, 1003, 2001, 2002].includes(errno)) {
          ElMessage.info(msg);
        } else {
          console.error('Error getting venue:', msg);
        }
      }).catch(error => {
        console.error('Error getting venue:', error);
      });
    },
    toUrl(url){
      window.open(url);
    },
    toScholar(scholarId){
      const scholar_id = scholarId;
      const route = this.$router.resolve({
        name: 'scholar', params: { scholar_id }
      });
      window.open(route.href, '_blank');
    },
    downloadWork(url) {
      window.open(url);
    },
    goTo(paperId){
      const paper_id = paperId;
      const route = this.$router.resolve({
        name: 'paper', params: { paper_id }
      });
      window.open(route.href, '_blank');
    },
    searchWorks() {
      const searchTerm = this.searchTerm.toLowerCase();
      switch (this.searchOption) {
        case 'title':
          this.works_search = this.works_list.filter(doc => doc.title.toLowerCase().includes(searchTerm));
          break;
        case 'author':
          this.works_search = this.works_list.filter(doc => {
            if (!doc.authorships || doc.authorships.length === 0) {
              return false; 
            }
            return doc.authorships.some(function (authorship) {
              return authorship.author.display_name.toLowerCase().includes(searchTerm);
            });
          });
        break;
        case 'date':
          this.works_search = this.works_list.filter(doc => doc.publication_date.toLowerCase().includes(searchTerm));
          break;
        default:
          this.works_search = this.works_list.filter(doc => {
            const titleMatch = doc.title.toLowerCase().includes(searchTerm);
            const authorMatch = doc.authorships && doc.authorships.length > 0 &&
              doc.authorships.some(authorship => authorship.author.display_name.toLowerCase().includes(searchTerm));
            const dateMatch = doc.publication_date.toLowerCase().includes(searchTerm);
            return titleMatch || authorMatch || dateMatch;
          });
          break;
      }
      this.updateWorksShow();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updateWorksShow();
    },
    updateWorksShow() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.works_show = this.works_search.slice(start, end);
    },
  }
};
</script>

<style scoped>
.whole-page {
  padding-left: 50px;
  padding-right: 50px;
}
.el-header {
  margin-top: 20px;
  margin-bottom: 20px;
}
.header-row {
  display: flex;
  align-items: center;
}

.main-content {
  overflow: auto;
}

.search-col {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  text-align: right;
  margin-right: 10px;
}

.option {
  width: 100px;
}

.input {
  flex: 1;
}

.el-row,
.el-col {
  margin: 0;
}

.headMain{
  color: rgba(30, 87, 141, 0.719);
}

.info{
  font-size:medium;
  color: #717171;
}

a {
    text-decoration: underline; /* 添加下划线 */
    color: inherit; /* 继承父元素的颜色，保持默认颜色 */
    cursor: pointer;
  }

a:hover {
    color: #193b80; /* 在悬停时变更颜色 */
  }

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 15px; 
}

</style>
